﻿using System;
using System.Windows.Forms;
using System.Collections;
using System.Data;


namespace OALPTool
{
    public class ISysPlatformFunc
    {
        public ISysPlatformFunc()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        ///	写日志
        ///	<param name = "strMsg">消息串</param>
        /// </summary>
        public static int WriteLog(string strMsg)
        {
            return TSysPublic.ExecFunction("ERPSysLog", strMsg);
        }

        /// <summary>
        /// 得到当前系统时间
        /// </summary>
        public static int GetCurrentTime(out DateTime dtCurrentTime)
        {
            object Result;
            Result = null;

            dtCurrentTime = DateTime.Now;

            if (TSysPublic.ExecFunction("GetCurrentTime", out Result) < 0)
            {
                TSysPublic.ShowErrMsg("函数调用错误！");
                return -1;
            }

            if (Result == null)
            {
                return -2;
            }

            dtCurrentTime = (DateTime)Result;

            return 0;
        }

        #region   公共处理函数
        #region 编码进制转换公共函数

        /// <summary>
        /// 编码10进制
        /// </summary>
        public const string StrCodeScale10 = "0123456789";
        /// <summary>
        /// 编码36进制
        /// </summary>
        public const string StrCodeScale36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        /// <summary>
        /// 把36进制的字符串转换成等效的整数
        /// 如果字符串为null或空串，返回-1
        /// 如果字符串中的字符是0～Z以外的字符，将抛出ArgumentOutOfRangeException异常
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int Str36ToInt(string str)
        {
            if (str == null || str == "")
                return -1;
            int result = 0;
            int index;
            for (int i = 0; i < str.Length; i++)
            {
                index = StrCodeScale36.IndexOf(str[i]);
                if (index < 0)
                    throw new System.ArgumentOutOfRangeException("str", str, "36进制字符串中的字符只能是0～Z！当前参数值为：" + str);
                result = result * 36 + index;
            }
            return result;
        }

        /// <summary>
        /// 把整数转换成等效的36进制的字符串
        /// 如果整数小于0，返回null
        /// 本函数不左补0，也不检查字符串长度
        /// 例如：0转换成"0",而不是"000";46655转换成"ZZZ";46656转换成"1000"
        /// </summary>
        /// <param name="iStr"></param>
        /// <returns></returns>
        public static string IntToStr36(int iStr)
        {
            if (iStr < 0)
                return null;
            System.Text.StringBuilder result = new System.Text.StringBuilder();
            int rest;//余数
            while (iStr >= 36)
            {
                iStr = Math.DivRem(iStr, 36, out rest);
                result.Insert(0, StrCodeScale36[rest]);
            }
            result.Insert(0, StrCodeScale36[iStr]);

            if (result.Length > 2) { }
            else if (result.Length > 1)
                result.Insert(0, "0");
            else
                result.Insert(0, "00");

            return result.ToString();
        }


        /// <summary>
        /// 获取下一个字符串
        /// 如果传入的字符串为null或空串，返回null
        /// 如果字符串中的字符是0～Z以外的字符，将抛出ArgumentOutOfRangeException异常
        /// 返回的字符串与传入的字符串长度相同。如果传入字符串已达最大值，返回null
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetNextStr(string str)
        {
            if (str == null || str == "")
                return null;
            System.Text.StringBuilder result = new System.Text.StringBuilder(str);

            int i = result.Length - 1;
            int index = StrCodeScale36.IndexOf(result[i]) + 1;
            if (index < 1)
                throw new System.ArgumentOutOfRangeException("str", str, "36进制字符串中的字符只能是0～Z！当前参数值为：" + str);
            while (index >= 36)
            {
                result[i] = '0';
                i--;
                if (i < 0)//已达最大值，返回null
                    return null;

                index = StrCodeScale36.IndexOf(result[i]) + 1;
                if (index < 1)
                    throw new System.ArgumentOutOfRangeException("str", str, "36进制字符串中的字符只能是0～Z！当前参数值为：" + str);
            }

            result[i] = StrCodeScale36[index];
            return result.ToString();
        }


        /// <summary>
        /// 36进制的字符串相减，用于取级别码的车轮算法
        /// 如果传入的字符串为null或空串，将抛出ArgumentOutOfRangeException异常
        /// 如果字符串中的字符是0～Z以外的字符，将抛出ArgumentOutOfRangeException异常
        /// </summary>
        /// <param name="a">被减数</param>
        /// <param name="b">减数</param>
        /// <returns></returns>
        public static int SubstractStr36(string a, string b)
        {
            if (a == null || a == "" || b == null || b == "")
                throw new System.ArgumentOutOfRangeException("被减数，减数", "36进制字符串的减法不允许被减数、减数为null或空串！");
            return Str36ToInt(a) - Str36ToInt(b);
        }

        #endregion

        #region 数据转换和数据处理公共函数

        /// <summary>
        /// 比较两个Decimal数

        /// </summary>
        /// <param name="d1"></param>
        /// <param name="d2"></param>
        /// <param name="decimals">比较的精度（小数位数）</param>
        /// <returns>返回d1-d2的值（大于0表示d1大于d2;等于0表示d1等于d2;小于0表示d1小于d2）</returns>
        public static decimal Compare(decimal d1, decimal d2, int decimals)
        {
            decimal d = Convert.ToDecimal("0." + "1".PadLeft(decimals, '0'));
            //			for(int i=0; i<decimals; i++)
            //			{
            //				d /= 10m;
            //			}
            decimal df = d1 - d2;
            if (df > -d && df < d)
            {
                return 0m;
            }
            return df;
        }

        /// <summary>
        /// 比较两个Decimal数(精度为8位小数，即0.12345678=0.123456789)
        /// </summary>
        /// <param name="d1"></param>
        /// <param name="d2"></param>
        /// <returns>返回d1-d2的值（大于0表示d1大于d2;等于0表示d1等于d2;小于0表示d1小于d2）</returns>
        public static decimal Compare(decimal d1, decimal d2)
        {
            return Compare(d1, d2, 8);
        }

        /// <summary>
        /// 转换成要保存到数据库的文本格式

        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ConvertToDbStr(object obj)
        {
            if (obj == null || obj.Equals(Convert.DBNull) || obj.ToString() == "")
            {
                return "default";
            }
            else
            {
                return " '" + obj.ToString().Replace("'", "''") + "'";
            }
        }

        /// <summary>
        /// 转换成要保存到数据库的数字格式
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ConvertToDbNum(object obj)
        {
            if (obj == null || obj.Equals(Convert.DBNull) || obj.ToString().Trim().Equals(""))
            {
                return "default";
            }
            else
            {
                return obj.ToString();
            }
        }

        #endregion

        /// <summary>
        /// 整理出规则的级别码

        /// </summary>
        /// <param name="dtSource">数据集中必须包含原有不整齐级别码字段TreeLevel
        ///                        生成新整齐级别码字段NewTreeLevel</param>
        internal int ConvertOrderLevel(ref DataTable dtSource, out string strMsg)
        {
            strMsg = "";

            try
            {
                if (dtSource == null)
                    return -1;

                if (!dtSource.Columns.Contains("TreeLevelLength"))
                    dtSource.Columns.Add("TreeLevelLength", typeof(int), "Len(TreeLevel)");
                if (!dtSource.Columns.Contains("NewTreeLevel"))
                    dtSource.Columns.Add("NewTreeLevel", typeof(string));
                if (!dtSource.Columns.Contains("NewTreeLevelLength"))
                    dtSource.Columns.Add("NewTreeLevelLength", typeof(int), "Len(NewTreeLevel)");

                DataView dvTemp = new DataView();

                dvTemp.Table = dtSource;

                dvTemp.RowFilter = "";
                dvTemp.Sort = "TreeLevel";

                int i = 0, j = 0;
                bool IfFind = false;
                string parNewLevel = "", parLevel = "";     //父节点原级别码

                int SortNo = 0;
                DataRow[] drs = null;

                DataRow dr = null, drold = null;

                if (dvTemp.Count > 0)
                {
                    dr = dvTemp[0].Row;
                    dr["NewTreeLevel"] = "000";
                    drold = dr;
                }

                for (i = 1; i < dvTemp.Count; i++)
                {
                    dr = dvTemp[i].Row;

                    //public static string GetNextStr(string str)

                    IfFind = false;
                    SortNo = 0;

                    for (j = 1; j < (dr["TreeLevel"].ToString().Trim().Length / 3); j++)
                    {
                        drs = dtSource.Select("TreeLevel = '" + dr["TreeLevel"].ToString().Trim().Remove(dr["TreeLevel"].ToString().Trim().Length - 3 * j, 3 * j) + "'  and NewTreeLevel is not null and TreeLevelLength < " + dr["TreeLevel"].ToString().Trim().Length, "TreeLevel");
                        if (drs.Length > 0)
                        {
                            IfFind = true;
                            parLevel = drs[0]["TreeLevel"].ToString();
                            parNewLevel = drs[0]["NewTreeLevel"].ToString();
                            break;
                        }
                    }

                    if (IfFind)
                    {
                        SortNo = dtSource.Select("TreeLevel like '" + parLevel + "%' and NewTreeLevel is not null and NewTreeLevelLength = " + Convert.ToInt32(parNewLevel.Length + 3)).Length;

                        dr["NewTreeLevel"] = drs[0]["NewTreeLevel"].ToString() + IntToStr36(SortNo);

                    }
                    else
                    {
                        SortNo = dtSource.Select("NewTreeLevelLength = 3").Length;
                        dr["NewTreeLevel"] = IntToStr36(SortNo);
                    }


                    drold = dr;
                }
            }
            catch (Exception e)
            {
                TSysPublic.ShowMsg(e.ToString());
            }

            return 0;
        }

        #endregion

        /// <summary>
        /// 显示帮助界面
        /// </summary>
        /// <param name="control">界面控件</param>
        /// <param name="FileIndex">文件名</param>
        /// <param name="KeyIndex">索引名称</param>
        public static void ShowFrmSys_Help(Control control, string FileIndex, string KeyIndex)
        {
            int sysret, ret;
            ArrayList args = new ArrayList();
            args.Add(control);
            args.Add(FileIndex);
            args.Add(KeyIndex);

            sysret = TSysPublic.ExecFunction("Sys_ShowHelp", ref args, out ret);
            if (sysret < 0)
            {
                TSysPublic.ShowMsg("调用Sys_ShowHelp方法失败！");
                return;
            }
            else if (ret < 0)
            {
                TSysPublic.ShowMsg("调用Sys_ShowHelp方法失败，失败码为" + ret.ToString());
                return;
            }
        }
    }
}
